<?php

namespace app\common\middleware;

use app\common\utils\CommonSign;
use app\common\utils\Res;

class ThirdAipAuth
{
    public function handle($request, \Closure $next)
    {
        if (env('APP_ENV') == 'local') {
            return $next($request);
        }
        $appid = $request->header('appId');
        if (!$appid) {
            return Res::error('请传递 appId');
        }
        if (!CommonSign::checkAppid($appid)) {
            return Res::error('appId不存在 请先申请#' . $request->header('appId'));
        }
        if (empty($request->header('timestamp'))) {
            return Res::error('请传递时间戳 (timestamp)');
        }
        if (empty($request->header('nonce'))) {
            return Res::error('请传递混淆参数 (nonce)');
        }
        if (empty($request->header('sign'))) {
            return Res::error('请传递参数签名 (sign)');
        }
        $params = $request->param();

        if (isset($params['appKey']) || $request->header('appKey')) {
            return Res::error('请不要传递 appKey');
        }
        $correctSign = CommonSign::commonSign($params, $appid, $request->header('timestamp'), $request->header('nonce'));
        // $correctSign2 = CommonSign::commonSign2($params, $appid, $request->header('timestamp'), $request->header('nonce'));
        if ($request->header('sign') !== $correctSign) {
            if (env('APP_ENV') != 'production') {
                $message = '签名错误, Debug 提示: 正确签名 ' . $correctSign;
            } else {
                $message = '签名错误';
            }
            return Res::error($message);
        }
        return $next($request);
    }
}
